<?php
//微信基本操作
class WechatBase{
	
	protected $Appid;
	protected $Secret;
	
	function __construct($appid,$secret){
		$this->Appid = $appid;
		$this->Secret = $secret;
	}
	
	protected function writeArr($fileName = 'config',$data){
		if(!is_array($data)){ return false; }
		$txt = "<?php\nreturn ".var_export($data,true).";\n?>";
		$length = file_put_contents(__DIR__ . '/wechat_cache/'.$fileName.'.php',$txt);
		return $length > 0;
	}
	protected function readArr($fileName = 'config'){
		$fpath = __DIR__ . '/wechat_cache/'.$fileName.'.php';
		if(!file_exists($fpath)){
			return null;
		}
		return include $fpath;
	}
	
	public function get_access_token(){
		$access_token = '';
		$data = $this->readArr('access_token');
		if(
			!empty($data['access_token']) && 
			!empty($data['expires'])
		){
			if($data['expires'] > time()){
				return $data['access_token'];
			}
		}
		$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";
		$url.= "&appid={$this->Appid}&secret=" . $this->Secret;
		$response = \HttpHelper::get($url);
		$data = json_decode($response,true);
		if(
			isset($data['access_token']) && 
			isset($data['expires_in'])
		){
			$access_token = $data['access_token'];
			$newdata = [
				'access_token' => $access_token,
				'expires' => time() + 7000
			];
			$this->writeArr('access_token',$newdata);
		}
		return $access_token;
	}
	
	public function getSignPackage() {
		$jsapiTicket = $this->getJsApiTicket();

		$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
		$url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

		$timestamp = time();
		$nonceStr = $this->createNonceStr();

		// 这里参数的顺序要按照 key 值 ASCII 码升序排序
		$string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";

		$signature = sha1($string);

		$signPackage = array(
			"appId"     => $this->Appid,
			"nonceStr"  => $nonceStr,
			"timestamp" => $timestamp,
			"url"       => $url,
			"signature" => $signature,
			"rawString" => $string
		);
		return $signPackage; 
	}
	//获取随机字符串
	public function createNonceStr($length = 16) {
		$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		$str = "";
		for ($i = 0; $i < $length; $i++) {
			$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
		}
		return $str;
	}
	
	//获取Ticket
	public function getJsApiTicket() {
		$data = $this->readArr('jsapi_ticket');
		if(
			!empty($data['jsapi_ticket']) && 
			!empty($data['expires'])
		){
			if($data['expires'] > time()){
				return $data['jsapi_ticket'];
			}
		}
		//重新获取
		$accessToken = $this->get_access_token();

		// 如果是企业号用以下 URL 获取 ticket
		// $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
		$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
		$res = json_decode(\HttpHelper::get($url),true);
		if(empty($res['ticket'])){
			return null;
		}
		$newData = [
			'jsapi_ticket' => $res['ticket'],
			'expires' => time() + 7000,
		];
		$this->writeArr('jsapi_ticket',$newData);

		return $res['ticket'];
	}


	
}